package com.example.demo.controller;

import com.example.demo.common.Appvariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.ResultAjax;
import com.example.demo.model.Userinfo;
import com.example.demo.model.vo.UserinfoVO;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yyx
 * Date: 2023-11-05
 * Time: 14:32
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public ResultAjax reg(Userinfo userinfo){
        //1.非空校验
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername()) ||
                 !StringUtils.hasLength(userinfo.getPassword())){
            return ResultAjax.fail(-1,"非法参数!");
        }

        //密码加盐
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        //2.执行业务代码
        int result = userService.reg(userinfo);
        //3.返回结果给前端
//        ResultAjax resultAjax = new ResultAjax();
//        resultAjax.setCode(result);
//        return resultAjax;
        return ResultAjax.succ(result);
    }

    @RequestMapping("/login")
    public ResultAjax login(UserinfoVO userinfoVO, HttpServletRequest request){//使用扩展类以防后序增加参数
        //1.参数校验  基本一致
        if(userinfoVO == null || !StringUtils.hasLength(userinfoVO.getUsername()) ||
                !StringUtils.hasLength(userinfoVO.getPassword())){
            return ResultAjax.fail(-1,"非法参数!");
        }
        //2.根据用户名查询对象  查到之后在根据密码匹配
        Userinfo userinfo = userService.getUserByName(userinfoVO.getUsername());
        if(userinfo==null || userinfo.getId() == 0){
            return ResultAjax.fail(-2,"用户名或密码错误");
        }
        //!userinfoVO.getPassword().equals(userinfo.getPassword())
        //3.使用对象中的密码和用户输入的密码进行校验(注意此时要取非!!特殊情况需要返回fail不然就继续创建会话)
        if(!PasswordUtils.decrypt(userinfoVO.getPassword(),userinfo.getPassword())){
            return ResultAjax.fail(-2,"用户名或密码错误!!");
        }
        //4.设置session会话保存用户状态!!!
        HttpSession session = request.getSession();
        session.setAttribute(Appvariable.SESSION_USERINFO_ID,userinfo);

        //5.返回数据(此时无须返回session,框架会自动返回)
        return ResultAjax.succ(1);//这个1不是状态码(固定200)是data
    }
    @RequestMapping("/logout")
    public ResultAjax logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);//没有session不可重新创建
        if(session != null || session.getAttribute(Appvariable.SESSION_USERINFO_ID)!=null){
            session.removeAttribute(Appvariable.SESSION_USERINFO_ID);
        }
        return ResultAjax.succ(1);
    }

}
